<template>
  <a-modal title="" width="70%" :visible="visible" @ok="submit" @cancel="cancelAdd">
    <a-form :form="form">
      <a-form-item label="名称">
        <a-input v-decorator="['name', { rules: [{ required: true, message: '请输入' }] }]" placeholder="" />
      </a-form-item>
      <a-form-item label="内容">
        <div id="toolbar-container-addGoods"></div>
        <div id="editor-addGoods"></div>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
  import MyUploadAdapter from '@/utils/MyUploadAdapter.js'
  import DecoupledEditor from '@ckeditor/ckeditor5-build-decoupled-document'
  import '@ckeditor/ckeditor5-build-decoupled-document/build/translations/zh-cn'
  import {
    knowledgeAdd,
    knowledgeUpdate
  } from '@/api/question'
  import {
    getFormData
  } from '@/utils/aliOss/aliossUpload.js'
  import aliOssConfig from '@/utils/aliOss/config'
  const formItemLayout = {
    labelCol: {
      span: 4
    },
    wrapperCol: {
      span: 8
    },
  };
  const formTailLayout = {
    labelCol: {
      span: 4
    },
    wrapperCol: {
      span: 8,
      offset: 4
    },
  };

  export default {
    props: {
      visible: {
        type: Boolean,
        required: true,
      }
    },
    data() {
      return {
        checkNick: false,
        formItemLayout,
        formTailLayout,
        form: this.$form.createForm(this),
        loading: false,
        imageUrl: '',
        formData: {},
        aliOssConfig: aliOssConfig,
        id: 0,
        updateflag: false,
        editor: ''
      };
    },
    created() {
      var that = this
      this.$watch('visible', (e) => {
        if (e) {
          if (!that.editor) {
            this.$nextTick(function() {
              setTimeout(function() {
                that.initEditor()
              }, 100)
            })
          }
        }
      })
    },
    methods: {
      initEditor() {
        var that = this
        DecoupledEditor.create(document.querySelector('#editor-addGoods'), {
            language: 'zh-cn',
            toolbar: {
              items: [
                'heading',
                '|',
                'fontfamily',
                'fontsize',
                '|',
                'alignment',
                '|',
                'fontColor',
                'fontBackgroundColor',
                '|',
                'bold',
                'italic',
                'strikethrough',
                'underline',
                'subscript',
                'superscript',
                '|',
                'link',
                '|',
                'outdent',
                'indent',
                '|',
                'bulletedList',
                'numberedList',
                'todoList',
                '|',
                'code',
                'codeBlock',
                '|',
                'insertTable',
                '|',
                'uploadImage',
                'blockQuote',
                '|',
                'undo',
                'redo',
              ],
              shouldNotGroupWhenFull: true,
            },
          })
          .then((editor) => {
            that.editor = editor
            const toolbarContainer = document.querySelector('#toolbar-container-addGoods')
            toolbarContainer.appendChild(editor.ui.view.toolbar.element)
            editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
              return new MyUploadAdapter(loader)
            }
          })
          .catch((error) => {
            console.error(error)
          })
      },

      cancelAdd() {
        this.updateflag = false
        this.$emit('cancel', true)
        this.form.resetFields()
        this.imageUrl = ''
      },
      setUpdate(formValue) {
        this.updateflag = true
        this.id = formValue.id
        this.form.setFieldsValue({
          name: formValue.name
        })
        if (this.editor) {
          this.editor.setData(formValue.content)
        } else {
          setTimeout(() => {
            this.editor.setData(formValue.content)
          }, 1000)
        }
      },
      submit() {
        var that = this
        const {
          form: {
            validateFields
          },
        } = this

        validateFields((errors, values) => {
          if (!errors) {
            var editorData = this.editor.getData();
            if (!editorData) {
              this.$message.warning('请编辑内容');
              return false
            }
            values.content = editorData
            if (this.updateflag) {
              values.id = this.id
              knowledgeUpdate({
                ...values,
              }).then((res) => {
                if (res.code == 0) {
                  that.form.resetFields()
                  that.$emit('ok')
                }
              })
            } else {
              knowledgeAdd({
                ...values,
              }).then((res) => {
                if (res.code == 0) {
                  that.form.resetFields()
                  that.$emit('ok')
                }
              })
            }
          }
        })
      },
      beforeUpload(file) {
        this.formData = getFormData()
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
        if (!isJpgOrPng) {
          this.$message.error('请上传图片类型文件!')
        }
        const isLt2M = file.size / 1024 / 1024 < 2
        if (!isLt2M) {
          this.$message.error('图片最大体积为2MB!')
        }
        return isJpgOrPng && isLt2M
      },
      check() {
        this.form.validateFields(err => {
          if (!err) {
            console.info('success');
          }
        });
      },
      handleChange(info) {
        if (info.file.status === 'uploading') {
          this.loading = true
          return
        }
        console.log(info.file.status)
        if (info.file.status == 'done') {
          this.imageUrl = this.aliOssConfig.uploadUrl + '/' + this.formData.key
          console.log(this.imageUrl)
          this.loading = false
        }
      },
    },
  };
</script>
<style>
  #editor-addGoods {
    min-height: 300px;
    max-height: 700px;
    overflow-y: auto;
    overflow-wrap: anywhere;
    word-break: break-word;
    background-color: #f9f9f9;
    color: #001234;
  }
</style>